package org.example.serialize;

import java.io.*;

// 结论：一个类如果需要可以被序列化，那么它必须实现了Serializable这个标记接口，同时它的所有成员也必须是可以序列化的
// 如果它包含了不可序列化的成员，那么在序列化的时候会抛出java.io.NotSerializableException
class NoSerializable {
    private String name;

    public NoSerializable(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "NoSerializable{" +
                "name='" + name + '\'' +
                '}';
    }
}

class TheSerializableImpl implements Serializable {
    private int age;

    private NoSerializable noSerializable;

    public TheSerializableImpl(int age, NoSerializable noSerializable) {
        this.age = age;
        this.noSerializable = noSerializable;
    }

    @Override
    public String toString() {
        return "TheSerializableImpl{" +
                "age=" + age +
                ", noSerializable=" + noSerializable +
                '}';
    }
}

public class NoSerializableTests {

    static void serialize() throws IOException{
        TheSerializableImpl theSerializable = new TheSerializableImpl(10, new NoSerializable("name"));
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("noSerializable.ser"))){
            oos.writeObject(theSerializable);
        }
    }

    static void deserialize() throws IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("noSerializable.ser"))){
            TheSerializableImpl theSerializable = (TheSerializableImpl) ois.readObject();
            System.out.println(theSerializable);
        }
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 虽然TheSerializableImpl实现了Serializable接口，但是由于它包含了一个没有实现Serializable接口的成员「NoSerializable」，所以它也无法被序列化
        serialize(); // 抛出：java.io.NotSerializableException: org.example.serialize.NoSerializable
        deserialize();
    }
}
